package com.chatroom.service;

import com.chatroom.dto.ChatMessage;
import com.chatroom.entity.Message;
import com.chatroom.entity.User;
import com.chatroom.repository.MessageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class MessageService {
    
    @Autowired
    private MessageRepository messageRepository;
    
    @Autowired
    private UserService userService;
    
    public Message saveMessage(ChatMessage chatMessage) {
        Message message = new Message();
        message.setContent(chatMessage.getContent());
        message.setMessageType(Message.MessageType.valueOf(chatMessage.getMessageType()));
        message.setRoomId(chatMessage.getRoomId());
        message.setCreatedAt(chatMessage.getTimestamp());
        
        // 设置发送者
        userService.getUserByUsername(chatMessage.getSender())
                .ifPresent(message::setSender);
        
        // 设置接收者（如果是私聊）
        if (chatMessage.getReceiver() != null) {
            userService.getUserByUsername(chatMessage.getReceiver())
                    .ifPresent(message::setReceiver);
        }
        
        return messageRepository.save(message);
    }
    
    public Page<Message> getRoomMessages(String roomId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return messageRepository.findByRoomIdOrderByCreatedAtDesc(roomId, pageable);
    }
    
    public Page<Message> getPrivateMessages(Long userId1, Long userId2, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return messageRepository.findPrivateMessages(userId1, userId2, pageable);
    }
    
    public List<Message> getSystemMessages() {
        return messageRepository.findSystemMessages();
    }
    
    public Message createSystemMessage(String content) {
        Message message = new Message();
        message.setContent(content);
        message.setMessageType(Message.MessageType.SYSTEM);
        message.setCreatedAt(LocalDateTime.now());
        
        // 系统消息不需要发送者
        return messageRepository.save(message);
    }
} 